import { RootState } from '@/types/store'
import { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'

export const useInitialState = <StateName extends keyof RootState>(action: () => void, stateName: StateName) => {
  // 发action 需要dispatch
  const dispatch = useDispatch()

  // 页面首次渲染完毕后发起请求
  useEffect(() => {
    // 发action
    dispatch(action())
  }, [dispatch])

  // 从redux读取数据
  return useSelector((state: RootState) => state[stateName])
}
